<template>
  <com-card>
    <div slot="com_header">修改密码嘞</div>
    <div slot="com_con">
      <el-row>
        <el-col :xs="24" :sm="8">
          <el-form :model="user" ref="userForm" :rules="checkPwd">
            <el-form-item label="原密码:" label-width="80px" prop="oldPwd">
              <el-input type="text" v-model="user.oldPwd"></el-input>
            </el-form-item>
            <el-form-item label="密码:" label-width="80px" prop="newPwd">
              <el-input type="text" v-model="user.newPwd"></el-input>
            </el-form-item>
            <el-form-item label="确认密码:" label-width="80px" prop="twoPwd">
              <el-input type="text" v-model="user.twoPwd"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button class="btn" type="primary" size="small" @click="save()"
                >提交</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
  </com-card>
</template>


<script>
import ComCard from "../../components/card";
import { api_editpwd, api_oldPwd } from "../../api/users.js";
export default {
  data() {
    // 验证原密码
    async function checkOldPWd(rule, value, callback) {
      let rst = await api_oldPwd({ oldPwd: value });
      let { msg, code } = rst;
      if (code == "00") {
        callback();
      } else {
        return callback(new Error(msg));
      }
    }
    // 验证新密码格式
    function checkPwd(rule, value, callback) {
      const reg = /^[a-zA-Z0-9]{3,12}$/gi;
      if (reg.test(value)) {
        callback();
      } else {
        return callback(new Error("请输入长度3-12的字母数字"));
      }
    }
    //验证确认密码
    const checkTwoPwd = (rule, value, callback) => {
      if (value == this.user.newPwd) {
        callback();
      } else {
        return callback(new Error("确认密码与新密码不一致！！"));
      }
    };
    return {
      user: {
        newPwd: "",
        oldPwd: "",
        twoPwd: "",
      },
      checkPwd: {
        newPwd: [
          {
            validator: checkPwd,
            trigger: "blur",
          },
        ],
        oldPwd: [{ validator: checkOldPWd, trigger: "blur" }],
        twoPwd: [
          {
            validator: checkTwoPwd,
            trigger: "blur",
          },
        ],
      },
    };
  },
  components: {
    ComCard,
  },
  methods: {
    save() {
      this.$refs.userForm.validate(async (b) => {
        if (b) {
          let rst = await api_editpwd(this.user);
          console.log(rst);
          let { code, msg } = rst;
          if (code == 0) {
            this.$message.success(msg);
            this.$local.remove("sell_token");
            this.$router.replace("/");
          }
        } else {
          console.log(b + "不通过");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.btn {
  margin-left: 350px;
}
</style>